import React, { useState } from 'react';
import { 
  Tree, Input, Button, Space, Dropdown, Menu, 
  Typography, Tooltip, Switch, message, Tag 
} from 'antd';
import {
  FolderOutlined, FileOutlined, EditOutlined,
  DeleteOutlined, PlusOutlined, SearchOutlined,
  DownOutlined, FolderOpenOutlined, HomeOutlined, TeamOutlined, UserOutlined,
  FileImageOutlined, FileWordOutlined, FilePdfOutlined
} from '@ant-design/icons';
import '../../../styles/tutorial.css';

const { Text } = Typography;
const { Search } = Input;

/**
 * Tree 树形控件教程
 * 展示 Tree 组件的核心特性和常见业务场景
 * 
 * 核心特性包括：
 * 1. 基础树形结构 - 展示层级数据
 * 2. 可选择树 - 单选/多选功能
 * 3. 可编辑树 - 节点的增删改
 * 4. 异步加载 - 动态加载子节点
 * 5. 搜索功能 - 节点过滤和高亮
 */
const TreeTutorial = () => {
  // 状态管理
  const [expandedKeys, setExpandedKeys] = useState(['0-0']);
  const [selectedKeys, setSelectedKeys] = useState([]);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [searchValue, setSearchValue] = useState('');

  /**
   * 示例数据
   * 模拟文件系统结构
   */
  const treeData = [
    {
      title: '项目文档',
      key: '0-0',
      children: [
        {
          title: '开发文档',
          key: '0-0-0',
          children: [
            { title: '前端规范.md', key: '0-0-0-0', isLeaf: true },
            { title: '接口文档.md', key: '0-0-0-1', isLeaf: true },
          ],
        },
        {
          title: '设计文档',
          key: '0-0-1',
          children: [
            { title: 'UI设计稿.sketch', key: '0-0-1-0', isLeaf: true },
            { title: '原型文件.rp', key: '0-0-1-1', isLeaf: true },
          ],
        },
      ],
    },
    {
      title: '源代码',
      key: '0-1',
      children: [
        { title: 'src', key: '0-1-0' },
        { title: 'tests', key: '0-1-1' },
        { title: 'docs', key: '0-1-2' },
      ],
    },
  ];

  /**
   * 自定义节点渲染
   * @param {Object} nodeData - 节点数据
   */
  const titleRender = (nodeData) => {
    const isLeaf = nodeData.isLeaf;
    const icon = isLeaf ? <FileOutlined /> : <FolderOutlined />;
    
    return (
      <Space>
        {icon}
        <Text>{nodeData.title}</Text>
        <Space size="small" className="node-actions" style={{ display: 'none' }}>
          <Tooltip title="编辑">
            <Button type="text" size="small" icon={<EditOutlined />} />
          </Tooltip>
          <Tooltip title="删除">
            <Button type="text" size="small" danger icon={<DeleteOutlined />} />
          </Tooltip>
        </Space>
      </Space>
    );
  };

  return (
    <div className="tutorial-container">
      <h1>Tree 树形控件</h1>

      {/* 1. 基础树形结构 */}
      <section className="example-section">
        <h2>1. 基础树形结构</h2>
        <div className="section-description">
          <p>展示基本的树形层级结构：</p>
          <ul>
            <li>节点展开/收起</li>
            <li>自定义图标</li>
            <li>节点选择</li>
          </ul>
        </div>
        <Tree
          treeData={treeData}
          defaultExpandedKeys={['0-0']}
          titleRender={titleRender}
          showIcon
        />
      </section>

      {/* 2. 可选择树 */}
      <section className="example-section">
        <h2>2. 可选择树</h2>
        <div className="section-description">
          <p>支持节点选择功能：</p>
          <ul>
            <li>单选/多选模式</li>
            <li>选择框联动</li>
            <li>半选状态</li>
          </ul>
        </div>
        <Space direction="vertical" style={{ width: '100%' }}>
          <Switch 
            checkedChildren="多选" 
            unCheckedChildren="单选"
            defaultChecked 
          />
          <Tree
            checkable
            treeData={treeData}
            checkedKeys={checkedKeys}
            onCheck={setCheckedKeys}
            titleRender={titleRender}
          />
        </Space>
      </section>

      {/* 3. 可编辑树 */}
      <section className="example-section">
        <h2>3. 可编辑树</h2>
        <div className="section-description">
          <p>实现树节点的编辑功能：</p>
          <ul>
            <li>节点的增加/删除</li>
            <li>节点名称编辑</li>
            <li>拖拽排序</li>
          </ul>
        </div>
        <Space direction="vertical" style={{ width: '100%' }}>
          <Space>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => {
                message.success('添加根节点');
              }}
            >
              添加根节点
            </Button>
          </Space>
          <Tree
            treeData={treeData}
            titleRender={(nodeData) => {
              const isLeaf = nodeData.isLeaf;
              const icon = isLeaf ? <FileOutlined /> : <FolderOutlined />;
              
              return (
                <Space>
                  {icon}
                  <Text>{nodeData.title}</Text>
                  <Space size="small">
                    <Tooltip title="添加子节点">
                      <Button 
                        type="text" 
                        size="small" 
                        icon={<PlusOutlined />}
                        onClick={(e) => {
                          e.stopPropagation();
                          message.success(`添加 ${nodeData.title} 的子节点`);
                        }}
                      />
                    </Tooltip>
                    <Tooltip title="编辑">
                      <Button 
                        type="text" 
                        size="small" 
                        icon={<EditOutlined />}
                        onClick={(e) => {
                          e.stopPropagation();
                          message.success(`编辑 ${nodeData.title}`);
                        }}
                      />
                    </Tooltip>
                    <Tooltip title="删除">
                      <Button 
                        type="text" 
                        size="small" 
                        danger 
                        icon={<DeleteOutlined />}
                        onClick={(e) => {
                          e.stopPropagation();
                          message.success(`删除 ${nodeData.title}`);
                        }}
                      />
                    </Tooltip>
                  </Space>
                </Space>
              );
            }}
            draggable
            blockNode
          />
        </Space>
      </section>

      {/* 4. 搜索过滤 */}
      <section className="example-section">
        <h2>4. 搜索过滤</h2>
        <div className="section-description">
          <p>实现树节点的搜索功能：</p>
          <ul>
            <li>关键字搜索</li>
            <li>搜索结果高亮</li>
            <li>自动展开匹配节点</li>
          </ul>
        </div>
        <Space direction="vertical" style={{ width: '100%' }}>
          <Search
            style={{ marginBottom: 8 }}
            placeholder="输入关键字搜索"
            onChange={(e) => {
              const value = e.target.value;
              setSearchValue(value);
              
              // 获取所有匹配的节点的父节点 key
              const expandedKeys = [];
              const searchNode = (nodes, parentKey) => {
                nodes.forEach((node) => {
                  if (node.title.indexOf(value) > -1) {
                    expandedKeys.push(parentKey);
                  }
                  if (node.children) {
                    searchNode(node.children, node.key);
                  }
                });
              };
              searchNode(treeData, '0');
              
              setExpandedKeys([...new Set(expandedKeys)]);
            }}
          />
          <Tree
            treeData={treeData.map(node => {
              const searchIndex = node.title.indexOf(searchValue);
              const beforeStr = node.title.substr(0, searchIndex);
              const afterStr = node.title.substr(searchIndex + searchValue.length);
              const title = searchIndex > -1 ? (
                <span>
                  {beforeStr}
                  <span style={{ color: '#f50' }}>{searchValue}</span>
                  {afterStr}
                </span>
              ) : (
                <span>{node.title}</span>
              );
              return {
                ...node,
                title,
              };
            })}
            expandedKeys={expandedKeys}
            titleRender={titleRender}
          />
        </Space>
      </section>

      {/* 5. 异步加载 */}
      <section className="example-section">
        <h2>5. 异步加载</h2>
        <div className="section-description">
          <p>实现异步加载子节点：</p>
          <ul>
            <li>动态加载数据</li>
            <li>加载状态显示</li>
            <li>异步操作处理</li>
          </ul>
        </div>
        <Tree
          loadData={(node) =>
            new Promise((resolve) => {
              setTimeout(() => {
                node.children = [
                  { title: `${node.title}-0`, key: `${node.key}-0` },
                  { title: `${node.title}-1`, key: `${node.key}-1` },
                ];
                resolve();
              }, 1000);
            })
          }
          treeData={[
            { title: '异步节点1', key: '0' },
            { title: '异步节点2', key: '1' },
          ]}
        />
      </section>

      {/* 6. 业务场景示例 */}
      <section className="example-section">
        <h2>6. 业务场景示例</h2>

        {/* 6.1 组织架构树 */}
        <div className="sub-section">
          <h3>6.1 组织架构树</h3>
          <div className="section-description">
            <p>常见的组织架构展示：</p>
            <ul>
              <li>部门层级展示</li>
              <li>人员信息展示</li>
              <li>快速检索定位</li>
            </ul>
          </div>
          <Tree
            showLine={{ showLeafIcon: false }}
            defaultExpandAll
            treeData={[
              {
                title: '总公司',
                key: 'company',
                children: [
                  {
                    title: '技术部',
                    key: 'tech',
                    children: [
                      { title: '前端组 (5人)', key: 'frontend' },
                      { title: '后端组 (8人)', key: 'backend' },
                      { title: '测试组 (3人)', key: 'qa' },
                    ],
                  },
                  {
                    title: '产品部',
                    key: 'product',
                    children: [
                      { title: '产品组 (4人)', key: 'pm' },
                      { title: 'UI设计组 (3人)', key: 'design' },
                    ],
                  },
                ],
              },
            ]}
            titleRender={(nodeData) => (
              <Space>
                {nodeData.key === 'company' ? <HomeOutlined /> : 
                 nodeData.children ? <TeamOutlined /> : <UserOutlined />}
                <Text>{nodeData.title}</Text>
              </Space>
            )}
          />
        </div>

        {/* 6.2 文件管理器 */}
        <div className="sub-section">
          <h3>6.2 文件管理器</h3>
          <div className="section-description">
            <p>文件系统管理功能：</p>
            <ul>
              <li>文件夹/文件展示</li>
              <li>右键菜单操作</li>
              <li>拖拽移动功能</li>
            </ul>
          </div>
          <Tree
            showIcon
            defaultExpandAll
            draggable
            treeData={[
              {
                title: '我的文档',
                key: 'docs',
                icon: <FolderOutlined />,
                children: [
                  {
                    title: '图片',
                    key: 'images',
                    icon: <FolderOutlined />,
                    children: [
                      { title: 'photo.jpg', key: 'photo', icon: <FileImageOutlined /> },
                      { title: 'avatar.png', key: 'avatar', icon: <FileImageOutlined /> },
                    ],
                  },
                  {
                    title: '文档',
                    key: 'documents',
                    icon: <FolderOutlined />,
                    children: [
                      { title: '说明.doc', key: 'doc', icon: <FileWordOutlined /> },
                      { title: '报告.pdf', key: 'pdf', icon: <FilePdfOutlined /> },
                    ],
                  },
                ],
              },
            ]}
            onRightClick={({ event, node }) => {
              event.preventDefault();
              message.info(`右键点击: ${node.title}`);
            }}
          />
        </div>

        {/* 6.3 权限管理树 */}
        <div className="sub-section">
          <h3>6.3 权限管理树</h3>
          <div className="section-description">
            <p>权限管理系统的树形结构：</p>
            <ul>
              <li>权限节点展示</li>
              <li>权限分配功能</li>
              <li>权限继承关系</li>
            </ul>
          </div>
          <Tree
            checkable
            defaultExpandAll
            treeData={[
              {
                title: '系统管理',
                key: 'system',
                children: [
                  {
                    title: '用户管理',
                    key: 'user',
                    children: [
                      { title: '用户列表', key: 'user-list' },
                      { title: '用户添加', key: 'user-add' },
                      { title: '用户编辑', key: 'user-edit' },
                    ],
                  },
                  {
                    title: '角色管理',
                    key: 'role',
                    children: [
                      { title: '角色列表', key: 'role-list' },
                      { title: '角色添加', key: 'role-add' },
                      { title: '角色编辑', key: 'role-edit' },
                    ],
                  },
                ],
              },
            ]}
            titleRender={(nodeData) => (
              <Space>
                <Text>{nodeData.title}</Text>
                <Tag color="blue">权限</Tag>
              </Space>
            )}
          />
        </div>

        {/* 6.4 分类管理树 */}
        <div className="sub-section">
          <h3>6.4 分类管理树</h3>
          <div className="section-description">
            <p>商品分类管理功能：</p>
            <ul>
              <li>多级分类展示</li>
              <li>分类排序功能</li>
              <li>分类状态管理</li>
            </ul>
          </div>
          <Tree
            draggable
            defaultExpandAll
            treeData={[
              {
                title: '电子产品',
                key: 'electronics',
                children: [
                  {
                    title: '手机',
                    key: 'phone',
                    children: [
                      { title: '智能手机', key: 'smart-phone' },
                      { title: '功能手机', key: 'feature-phone' },
                    ],
                  },
                  {
                    title: '电脑',
                    key: 'computer',
                    children: [
                      { title: '笔记本', key: 'laptop' },
                      { title: '台式机', key: 'desktop' },
                    ],
                  },
                ],
              },
            ]}
            titleRender={(nodeData) => (
              <Space>
                <Text>{nodeData.title}</Text>
                <Tag color="green">分类</Tag>
              </Space>
            )}
          />
        </div>
      </section>

      {/* 7. 性能优化建议 */}
      <section className="example-section">
        <h2>7. 性能优化建议</h2>
        <div className="section-description">
          <p>Tree 组件性能优化的关键点：</p>
          <ul>
            <li>大数据量处理
              <ul>
                <li>使用虚拟滚动（virtual scrolling）</li>
                <li>按需加载数据（异步加载）</li>
                <li>合理的数据分页策略</li>
              </ul>
            </li>
            <li>渲染优化
              <ul>
                <li>使用 React.memo 优化节点渲染</li>
                <li>避免不必要的重渲染</li>
                <li>优化自定义渲染函数</li>
              </ul>
            </li>
            <li>交互优化
              <ul>
                <li>合理的展开/收起策略</li>
                <li>优化搜索性能</li>
                <li>缓存搜索结果</li>
              </ul>
            </li>
          </ul>
        </div>

        {/* 7.1 使用 React.memo 优化渲染 */}
        <div className="sub-section">
          <h3>7.1 节点渲染优化</h3>
          <div className="section-description">
            <p>使用 React.memo 优化节点渲染性能：</p>
            <ul>
              <li>避免不必要的重复渲染</li>
              <li>仅当节点数据变化时重新渲染</li>
              <li>配合 shouldComponentUpdate 使用</li>
            </ul>
          </div>
          
          {/* 优化后的节点组件 */}
          {`
          const MemoTreeNode = React.memo(
            ({ nodeData }) => (
              <Space>
                {nodeData.isLeaf ? <FileOutlined /> : <FolderOutlined />}
                <Text>{nodeData.title}</Text>
              </Space>
            ),
            (prevProps, nextProps) => 
              prevProps.nodeData.title === nextProps.nodeData.title &&
              prevProps.nodeData.isLeaf === nextProps.nodeData.isLeaf
          );
          `}
        </div>

        {/* 7.2 虚拟滚动示例 */}
        <div className="sub-section">
          <h3>7.2 虚拟滚动处理</h3>
          <div className="section-description">
            <p>处理大数据量的虚拟滚动方案：</p>
            <ul>
              <li>使用 react-virtualized 库</li>
              <li>仅渲染可视区域节点</li>
              <li>动态计算节点高度</li>
            </ul>
          </div>
          
          {/* 虚拟滚动代码示例 */}
          {`
          import { AutoSizer, List } from 'react-virtualized';
          
          const VirtualTree = ({ treeData }) => {
            const flattenData = /* 平铺树形数据的方法 */;
            
            const rowRenderer = ({ index, key, style }) => (
              <div key={key} style={style}>
                {flattenData[index].title}
              </div>
            );

            return (
              <AutoSizer>
                {({ height, width }) => (
                  <List
                    height={height}
                    width={width}
                    rowCount={flattenData.length}
                    rowHeight={32}
                    rowRenderer={rowRenderer}
                  />
                )}
              </AutoSizer>
            );
          };
          `}
        </div>

        {/* 7.3 数据分页示例 */}
        <div className="sub-section">
          <h3>7.3 数据分页策略</h3>
          <div className="section-description">
            <p>分页加载树形数据方案：</p>
            <ul>
              <li>结合后端分页接口</li>
              <li>动态加载子树数据</li>
              <li>分页参数管理</li>
            </ul>
          </div>
          
          {/* 分页代码示例 */}
          {`
          const loadTreeData = async (node) => {
            const params = {
              parentId: node?.key || '0',
              page: node?.page || 1,
              pageSize: 10
            };

            const result = await api.getTreeData(params);
            
            return {
              ...node,
              children: result.data,
              page: params.page + 1,
              hasMore: result.total > params.page * params.pageSize
            };
          };
          `}
        </div>
      </section>
    </div>
  );
};

// 添加虚拟滚动样式
const styles = {
  virtualList: {
    border: '1px solid #f0f0f0',
    borderRadius: '4px',
    marginTop: '16px'
  }
};

export default TreeTutorial; 